package com.example.quarkus.service;

import com.example.quarkus.config.RuoYiConfig;
import com.example.quarkus.entity.Emp;
import com.example.quarkus.exception.BusinessException;
import com.example.quarkus.mapper.EmpMapper;
import io.quarkus.cache.CacheKey;
import io.quarkus.cache.CacheResult;
import io.quarkus.redis.datasource.RedisDataSource;
import io.quarkus.redis.datasource.value.ValueCommands;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import org.jboss.logging.Logger;

/**
 * @author: Hu Shan
 * @date: 2023/3/23 19:52
 * @description: TODO
 */

@ApplicationScoped
@Slf4j
public class EmpService {
    @Inject
    EmpMapper empMapper;

    @Inject
    RedisDataSource redisDataSource;

    public Emp getEmpById(Integer id) {
        Emp emp = empMapper.selectByPrimaryKey(id);
        if (emp == null){
            log.info("There is no data in mysql with id=" + id);
            throw new BusinessException("No Emp with id=" + id);
        }
        return emp;
    }

    @CacheResult(cacheName = "empQuarkus")
    public Emp getEmpForCache(@CacheKey Integer id) {
        log.info("getEmpForCache in service: " + id);
        Emp emp = empMapper.selectByPrimaryKey(id);
        if (emp == null){
            throw new BusinessException("No Emp with id=" + id + " in getEmpForRedis");
        }
        return emp;
    }

    public void setEmpByIdToRedis(Integer id) {
        ValueCommands<String, Emp> redisValueCommands = redisDataSource.value(String.class, Emp.class);
        Emp emp = getEmpById(id);
        redisValueCommands.set("emp" + id, emp);
    }

    public void insertEmp(Emp emp) {
        empMapper.insertSelective(emp);
    }

    public int updateEmp(Emp emp) {
        return empMapper.updateByPrimaryKeySelective(emp);
    }

    public int deleteEmp(int id) {
        return empMapper.deleteByPrimaryKey(id);
    }
}
